package emediashared;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import emediashared.ui.notifications.EventNotifier;

/**
 * The activator class controls the plug-in life cycle
 */
public class SharedActivator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "eMediaShared"; //$NON-NLS-1$

	// The shared instance
	private static SharedActivator plugin;
	
	/**
	 * The constructor
	 */
	public SharedActivator() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static SharedActivator getDefault() {
		return plugin;
	}

	public void logException(Exception e) {
		logException(null, e);
	}
	
	public void logException(String message, Exception e) {
		message = message == null ? e.getMessage() : message;
		getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, message, e));
	}
	
	public static void showAndLogError(Exception e) {
	   showAndLogError("Error", null, e);
	}

	public static void showAndLogError(String title, String message, Exception e) {
	    if (message == null) {
	    	message = e.getMessage();
	    } else {
	    	message = message + ". Reason: " + e.getMessage();
	    }
	    SharedActivator activator = getDefault();
	    if (activator != null) {
	    	activator.logException(message, e);
	    	EventNotifier.notifyError(title, message, EventNotifier.showViewRunnable("org.eclipse.pde.runtime.LogView"));
	    } else {
	    	e.printStackTrace();
	    }
	}
}
